package com.huicoo.forestmanager.ui.qr_helper.utils;

import android.graphics.Bitmap;
import android.graphics.Matrix;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.util.Hashtable;

/**
 * Created by lixl on 2017/2/17.
 * 二维码工具类
 */

public class QRCodeUtils {

    public static Bitmap createCode(int CODE_WIDTH, String url) {
        try {
            //判断URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//设置容错级别,H为最高
            hints.put(EncodeHintType.MARGIN, 0);//设置白色边距值
            //图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_WIDTH, hints);
            int[] pixels = new int[CODE_WIDTH * CODE_WIDTH];
            //下面这里按照二维码的算法，逐个生成二维码的图片，
            //两个for循环是图片横列扫描的结果
            for (int y = 0; y < CODE_WIDTH; y++) {
                for (int x = 0; x < CODE_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * CODE_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * CODE_WIDTH + x] = 0xffffffff;
                    }
                }
            }
            //生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(CODE_WIDTH, CODE_WIDTH, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, CODE_WIDTH, 0, 0, CODE_WIDTH, CODE_WIDTH);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成带LOGO的二维码
     */
    public static Bitmap createCode(int CODE_WIDTH, String url, Bitmap logoBitmap) {
        try {
            //判断URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            int BLACK = 0xFF000000;
            int WHITE = 0xFFFFFFFF;
            int LOGO_WIDTH_MAX = CODE_WIDTH / 10;
            int LOGO_WIDTH_MIN = CODE_WIDTH / 15;
            int logoWidth = logoBitmap.getWidth();
            int logoHeight = logoBitmap.getHeight();
            int logoHaleWidth = logoWidth >= CODE_WIDTH ? LOGO_WIDTH_MIN : LOGO_WIDTH_MAX;
            int logoHaleHeight = logoHeight >= CODE_WIDTH ? LOGO_WIDTH_MIN : LOGO_WIDTH_MAX;
            // 将logo图片按martix设置的信息缩放
            Matrix m = new Matrix();
            float sx = (float) 2 * logoHaleWidth / logoWidth;
            float sy = (float) 2 * logoHaleHeight / logoHeight;
            m.setScale(sx, sy);// 设置缩放信息
            Bitmap newLogoBitmap = Bitmap.createBitmap(logoBitmap, 0, 0, logoWidth, logoHeight, m, false);
            int newLogoWidth = newLogoBitmap.getWidth();
            int newLogoHeight = newLogoBitmap.getHeight();
            Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//设置容错级别,H为最高
            hints.put(EncodeHintType.MAX_SIZE, LOGO_WIDTH_MAX);// 设置图片的最大值
            hints.put(EncodeHintType.MIN_SIZE, LOGO_WIDTH_MIN);// 设置图片的最小值
            hints.put(EncodeHintType.MARGIN, 0);//设置白色边距值
            // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
            BitMatrix matrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_WIDTH, hints);
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            int halfW = width / 2;
            int halfH = height / 2;
            // 二维矩阵转为一维像素数组,也就是一直横着排了
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                /*
                 * 取值范围,可以画图理解下
				 * halfW + newLogoWidth / 2 - (halfW - newLogoWidth / 2) = newLogoWidth
				 * halfH + newLogoHeight / 2 - (halfH - newLogoHeight) = newLogoHeight
				 */
                    if (x > halfW - newLogoWidth / 2 && x < halfW + newLogoWidth / 2
                            && y > halfH - newLogoHeight / 2 && y < halfH + newLogoHeight / 2) {// 该位置用于存放图片信息
                    /*
                     *  记录图片每个像素信息
					 *  halfW - newLogoWidth / 2 < x < halfW + newLogoWidth / 2
					 *  --> 0 < x - halfW + newLogoWidth / 2 < newLogoWidth
					 *   halfH - newLogoHeight / 2  < y < halfH + newLogoHeight / 2
					 *   -->0 < y - halfH + newLogoHeight / 2 < newLogoHeight
					 *   刚好取值newLogoBitmap。getPixel(0-newLogoWidth,0-newLogoHeight);
					 */
                        pixels[y * width + x] = newLogoBitmap.getPixel(
                                x - halfW + newLogoWidth / 2, y - halfH + newLogoHeight / 2);
                    } else {
                        pixels[y * width + x] = matrix.get(x, y) ? BLACK : WHITE;// 设置信息
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            // 通过像素数组生成bitmap,具体参考api
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }
}
